<?php
namespace App\Webdisk;
function getFileSize($path){
    $size = filesize($path);
    $showSize = $size;
    $suffix = "Byte";
    if($size > 1024 && $size <= 1048576){
        $suffix = "KiB";
        $showSize = $size/1024;
    }else if($size > 1048576 && $size <= 1073741824){
        $suffix = "MiB";
        $showSize = $size/1048576;
    }else if($size > 1073741824){
        $suffix = "GiB";
        $showSize = $size/1073741824;
    }
    return round($showSize,2).' '.$suffix;
}

function getSuffix($fileName){
    $tmp = explode('.',$fileName);
    return strtolower($tmp[count($tmp) - 1]);
}

function getImagePreview($filePath,$baseWidth){
    $suffix = getSuffix($filePath);
    if(!preg_match("/jpg|png|gif|jpeg/",$suffix)){
        return "";
    }

    $md5 = md5_file($filePath);
    $previewFilePath = PREVIEW_IMAGE_DIR."/{$md5}.jpg";
    $url = PREVIEW_PREFIX."/$md5.jpg";
    if(file_exists($previewFilePath)){
        return $url;
    }

    $imgInfo = getimagesize($filePath);
    $imgMime = $imgInfo['mime'];
    $imgWidth = $imgInfo[0];
    $imgHeight = $imgInfo[1];
    $imgRatio = $imgHeight / $imgWidth; // 计算长宽比
    $imageData = null;

    switch ($imgMime) {
        case 'image/jpeg':$imageData = imagecreatefromjpeg($filePath);break;
        case 'image/png':$imageData = imagecreatefrompng($filePath);break;
        case 'image/gif':$imageData = imagecreatefromgif($filePath);break;
        default: return false;
    }
    $res = imagecreatetruecolor($baseWidth,$baseWidth*$imgRatio);
    imagecopyresampled($res,$imageData,0,0,0,0,$baseWidth,$baseWidth*$imgRatio,$imgWidth,$imgHeight);
    imagejpeg($res,$previewFilePath);
    return $url;
}

function getQueryString(){
    preg_match('/(?=\?).*/',$_SERVER['REQUEST_URI'],$preg);
    $queryString = "";
    if($preg){
        $queryString = $preg[0];
    }
    return $queryString;
}

/**
 * 构造标准响应数组结构
 * @param int $status 状态
 * @param mixed $data 有效数据
 * @param string $msg 服务器消息
 * @return array
 *
 */
function makeRes($status = 1, $data = null, $msg = "OK"){
    return [
        'status'=>$status,
        'data'=>$data,
        'msg'=>$msg
    ];
}

class SecurityUtils{
    static function hashPassword($origin_pwd){
        return md5(SALT.$origin_pwd);
    }

    static function hashUtoken($hash_pwd){
        return md5(getdate().$hash_pwd);
    }
}

/**
 * 取硬盘设备信息
 * @param string 设备路径
 */
function getDiskInfo($device_path){
    $awk = 'awk \'{ printf("{\"partition\":\"%s\",\"total\":%d,\"used\":%d,\"free\":%d,\"mount\":\"%s\"},\n",$1,$2,$3,$4,$6) }\'';
    $cmd = "df --block-size=1 | grep -E \"$device_path\" | sort | $awk";
    exec($cmd,$output);
    $output = implode('',$output);
    $res = "[$output";
    $res[strlen($res) - 1] = ']';
    return json_decode($res,true);
}
